﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// Класс, упрощающий работу с ресурсами/ассетами
/// </summary>

public class ResourceUtils
{
	public static string SUBDIR_LEVELS = "levels/";
	public static string SUBDIR_TEXTURES = "textures/";
	public static string SUBDIR_PREFABS = "prefabs/";
	public static string SUBDIR_ENTITY_PREFABS = SUBDIR_PREFABS + "entities/";
	public static string SUBDIR_GUI_PREFABS = SUBDIR_PREFABS + "gui/";
	public static string SUBDIR_MUSIC = "music/";
	public static string SUBDIR_SOUNDS = "sounds/";
	public static string SUBDIR_MATERIALS = "materials/";
	
	/// <summary>
	/// Кэш ассетов
	/// </summary>
	private static Hashtable cachedResources = new Hashtable();

	public static TextAsset GetLevel( string name )
	{
		return GetResource( SUBDIR_LEVELS + name, typeof( TextAsset ), false ) as TextAsset;
	}

	public static Texture GetTexture( string name )
	{
		return GetResource( SUBDIR_TEXTURES + name, typeof( Texture ), true ) as Texture;
	}

	public static GameObject GetPrefab( string name )
	{
		return GetResource( SUBDIR_PREFABS + name, typeof( GameObject ), true ) as GameObject;
	}

	public static GameObject GetEntityPrefab( string name )
	{
		return GetResource( SUBDIR_ENTITY_PREFABS + name, typeof( GameObject ), true ) as GameObject;
	}

	public static GameObject GetGUIPrefab( string name )
	{
		return GetResource( SUBDIR_GUI_PREFABS + name, typeof( GameObject ), true ) as GameObject;
	}

	public static AudioClip GetMusic( string name )
	{
		return GetResource( SUBDIR_MUSIC + name, typeof( AudioClip ), true ) as AudioClip;
	}

	public static AudioClip GetSound( string name )
	{
		return GetResource( SUBDIR_SOUNDS + name, typeof( AudioClip ), true ) as AudioClip;
	}

	public static Material GetMaterial( string name )
	{
		return GetResource( SUBDIR_MATERIALS + name, typeof( Material ), true ) as Material;
	}

	private static Object GetResource( string path, System.Type type, bool cache )
	{
		// Ищем в кэше
		if ( cachedResources.ContainsKey( path ) )
			return cachedResources[ path ] as Object;

		Object obj = Resources.Load( path, type );
		if ( !obj ) {
			Debug.LogError( "Файл не найден [" + type + "]\n" + path );
			return null;
		}

		if ( cache )
			cachedResources[ path ] = obj;

		return obj;
	}
}
